package com.ca.project.Server.Common.Listenner;

import lombok.extern.log4j.Log4j2;
import org.springframework.boot.ansi.AnsiColor;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

/**
 * 项目启动成功日志打印监听器
 *
 * @PACKAGE_NAME: com.ca.project.Common.Listenner
 * @NAME: StartedListener
 * @USER: ASUS
 * @DATE: 2023/8/28
 * @TIME: 下午 04:56
 **/
@Component
@Log4j2
public class StartedListener implements ApplicationListener<ApplicationReadyEvent> {
    /**
     * 项目启动成功将会在日志中输出对应的启动信息
     *
     * @param applicationReadyEvent 应用程序准备好事件
     */
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        String serverPort = applicationReadyEvent.getApplicationContext().getEnvironment().getProperty("server.port");
        String serverUrl = String.format("http://%s:%s", "127.0.0.1", serverPort);
        log.info(AnsiOutput.toString(AnsiColor.BRIGHT_BLUE, "CAStudio server started at:", serverUrl));
        if (checkShowServerDoc(applicationReadyEvent.getApplicationContext()))
            log.info(AnsiOutput.toString(AnsiColor.BRIGHT_BLUE, "CAStudio server`s doc started at:", serverUrl + "/doc.html"));
        log.info(AnsiOutput.toString(AnsiColor.BRIGHT_YELLOW, "CAStudio server has started successfully!"));
    }

    /**
     * 校验是否开始接口文档
     *
     * @param applicationContext 应用程序上下文
     * @return boolean
     */
    private boolean checkShowServerDoc(ConfigurableApplicationContext applicationContext) {
        return applicationContext.getEnvironment().getProperty("swagger2.show", Boolean.class, true) &&
                applicationContext.containsBean("swagger2Config");
    }
}
